package com.chaoyue.learning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chaoyue.base.exception.ChaoYuePlusException;
import com.chaoyue.content.beans.po.CoursePublish;
import com.chaoyue.learning.beans.dto.CyChooseCourseDto;
import com.chaoyue.learning.beans.dto.CyCourseTablesDto;
import com.chaoyue.learning.beans.po.CyChooseCourse;
import com.chaoyue.learning.beans.po.CyCourseTables;

import com.chaoyue.learning.feignclient.ContentServiceClient;
import com.chaoyue.learning.mapper.CyChooseCourseMapper;
import com.chaoyue.learning.mapper.CyCourseTablesMapper;
import com.chaoyue.learning.service.MyCourseTablesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@SuppressWarnings({"all"})
/**
 * @author whr
 * @version 1.0
 * @description: 添加课程服务实现类
 * @date 2023/5/30 21:26
 */
//学习资格状态 [{"code":"702001","desc":"正常学习"},{"code":"702002","desc":"没有选课或选课后没有支付"},{"code":"702003","desc":"已过期需要申请续期或重新支付"}]
@Service
@Slf4j
public class MyCourseTablesServiceImpl implements MyCourseTablesService {
    @Autowired
    CyChooseCourseMapper chooseCourseMapper;
    @Autowired
    CyCourseTablesMapper courseTablesMapper;
    @Autowired
    ContentServiceClient contentServiceClient;

    @Transactional
    @Override
    public CyChooseCourseDto addChooseCourse(String userId, Long courseId) {
        CoursePublish coursepublish = contentServiceClient.getCoursepublish(courseId);
        if (coursepublish == null) {
            ChaoYuePlusException.cast("该课程未发布,不能添加课程");
        }
        CyChooseCourse xcChooseCourse = null;
        String charge = coursepublish.getCharge();
        if (charge.equals("201000")) {
            //免费课程插入选课表
            xcChooseCourse = addFreeCourse(userId, coursepublish);
            //插入我的课程表
            CyCourseTables xcCourseTables = addCourseTables(xcChooseCourse.getId().toString());
        } else {
            //插入选课记录表
            xcChooseCourse = addChargeCourse(userId, coursepublish);
        }
        //封装返回属性
        CyChooseCourseDto xcChooseCourseDto = new CyChooseCourseDto();
        BeanUtils.copyProperties(xcChooseCourse, xcChooseCourseDto);
        //查询学习状态
        CyCourseTablesDto learningStatus = getLearningStatus(userId, courseId);
        xcChooseCourseDto.setLearnStatus(learningStatus.learnStatus);
        return xcChooseCourseDto;
    }

    //获取用户学习状态
    @Override
    public CyCourseTablesDto getLearningStatus(String userId, Long courseId) {
        CyCourseTables xcCourseTables = getXcCourseTables(userId, courseId);
        if (xcCourseTables == null) {
            CyCourseTablesDto xcCourseTablesDto = new CyCourseTablesDto();
            //没有选课或选课后没有支付
            xcCourseTablesDto.setLearnStatus("702002");
            return xcCourseTablesDto;
        }
        CyCourseTablesDto xcCourseTablesDto = new CyCourseTablesDto();
        BeanUtils.copyProperties(xcCourseTables, xcCourseTablesDto);
        //判断是否过期，截止时间在当前时间之前即为过期
        boolean before = xcCourseTables.getValidtimeEnd().isBefore(LocalDateTime.now());
        if (!before) {
            //正常学习
            xcCourseTablesDto.setLearnStatus("702001");
            return xcCourseTablesDto;
        } else {
            //过期
            xcCourseTablesDto.setLearnStatus("702003");
            return xcCourseTablesDto;
        }

    }

    @Transactional
    @Override
    public boolean saveChooseCourseStatus(String choosecourseId) {
        CyChooseCourse xcChooseCourse = chooseCourseMapper.selectById(choosecourseId);
        if (xcChooseCourse == null) {
            log.debug("选课记录不存在,id{}", choosecourseId);
            return false;
        }
        String status = xcChooseCourse.getStatus();
        if (status.equals("701002")) {
            xcChooseCourse.setStatus("701001");
            int i = chooseCourseMapper.updateById(xcChooseCourse);
            if(i<=0){
                log.debug("更新选课记录课程状态失败，选课id{}",choosecourseId);
                ChaoYuePlusException.cast("更新选课记录失败");
            }
            addCourseTables(choosecourseId);
        }
        return true;
    }

    public CyChooseCourse addFreeCourse(String userId, CoursePublish coursepublish) {
        LambdaQueryWrapper<CyChooseCourse> queryWrapper = new LambdaQueryWrapper<>();
        //查询是否有重复数据
        queryWrapper.eq(CyChooseCourse::getCourseId, coursepublish.getId())
                .eq(CyChooseCourse::getUserId, userId)
                .eq(CyChooseCourse::getOrderType, "700001")
                .eq(CyChooseCourse::getStatus, "701001");
        List<CyChooseCourse> xcChooseCourses = chooseCourseMapper.selectList(queryWrapper);
        if (xcChooseCourses != null && xcChooseCourses.size() > 0) {
            return xcChooseCourses.get(0);
        }
        CyChooseCourse xcChooseCourse = new CyChooseCourse();
        xcChooseCourse.setUserId(userId);
        xcChooseCourse.setCompanyId(coursepublish.getCompanyId());
        xcChooseCourse.setCourseId(coursepublish.getId());
        xcChooseCourse.setCourseName(coursepublish.getName());
        xcChooseCourse.setCreateDate(LocalDateTime.now());
        xcChooseCourse.setOrderType("700001");
        xcChooseCourse.setCoursePrice(coursepublish.getPrice());
        xcChooseCourse.setValidDays(365);
        xcChooseCourse.setStatus("701001");
        xcChooseCourse.setValidtimeStart(LocalDateTime.now());
        xcChooseCourse.setValidtimeEnd(LocalDateTime.now().plusDays(365));
        int insert = chooseCourseMapper.insert(xcChooseCourse);
        if (insert <= 0) {
            ChaoYuePlusException.cast("添加选课记录失败");
        }
        return xcChooseCourse;
    }

    //添加收费课程
    public CyChooseCourse addChargeCourse(String userId, CoursePublish coursepublish) {

        LambdaQueryWrapper<CyChooseCourse> queryWrapper = new LambdaQueryWrapper<>();
        //查询是否有重复数据
        queryWrapper.eq(CyChooseCourse::getCourseId, coursepublish.getId())
                .eq(CyChooseCourse::getUserId, userId)
                .eq(CyChooseCourse::getOrderType, "700002")
                .eq(CyChooseCourse::getStatus, "701002");
        List<CyChooseCourse> xcChooseCourses = chooseCourseMapper.selectList(queryWrapper);
        if (xcChooseCourses != null && xcChooseCourses.size() > 0) {
            return xcChooseCourses.get(0);
        }
        CyChooseCourse xcChooseCourse = new CyChooseCourse();
        xcChooseCourse.setUserId(userId);
        xcChooseCourse.setCompanyId(coursepublish.getCompanyId());
        xcChooseCourse.setCourseId(coursepublish.getId());
        xcChooseCourse.setCourseName(coursepublish.getName());
        xcChooseCourse.setCreateDate(LocalDateTime.now());
        xcChooseCourse.setOrderType("700002");
        xcChooseCourse.setCoursePrice(coursepublish.getPrice());
        xcChooseCourse.setValidDays(365);
        xcChooseCourse.setStatus("701002");
        xcChooseCourse.setValidtimeStart(LocalDateTime.now());
        xcChooseCourse.setValidtimeEnd(LocalDateTime.now().plusDays(365));
        int insert = chooseCourseMapper.insert(xcChooseCourse);
        if (insert <= 0) {
            ChaoYuePlusException.cast("添加选课记录失败");
        }
        return xcChooseCourse;
    }

    //添加到我的课程表
    public CyCourseTables addCourseTables(String choosecourseId) {
        CyChooseCourse xcChooseCourse = chooseCourseMapper.selectById(choosecourseId);
        if (xcChooseCourse == null) {

        }
        String status = xcChooseCourse.getStatus();
        if (!"701001".equals(status)) {
            ChaoYuePlusException.cast("选课失败");
        }
        CyCourseTables xcCourseTables = getXcCourseTables(xcChooseCourse.getUserId(), xcChooseCourse.getCourseId());
        if (xcCourseTables != null) {
            return xcCourseTables;
        }
        xcCourseTables = new CyCourseTables();
        BeanUtils.copyProperties(xcChooseCourse, xcCourseTables);
        xcCourseTables.setChooseCourseId(xcChooseCourse.getId());
        xcCourseTables.setCourseType(xcChooseCourse.getOrderType());
        courseTablesMapper.insert(xcCourseTables);
        return xcCourseTables;

    }

    public CyCourseTables getXcCourseTables(String userId, Long courseId) {
        LambdaQueryWrapper<CyCourseTables> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CyCourseTables::getUserId, userId)
                .eq(CyCourseTables::getCourseId, courseId);
        return courseTablesMapper.selectOne(queryWrapper);
    }
}
